﻿<%@ WebHandler Language="C#" Class="RbContainerShipTZReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 热表零组件收发台账报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date: 2022.8.17
 **/

public class RbContainerShipTZReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getSearchSqlString(JObject jObject)
    {
        string sql = @"
SELECT DISTINCT cci.mfgordername,f.factoryname fromfactory,cci.productname,cci.productdescription,cci.containername,
       subc.containername rbcontainername,cci.familylistnames,ws.workflowstepname,s.specno,
       CASE WHEN csr.recivedate IS NOT NULL THEN (csr.acceptanceqty +csr.lossqty) ELSE cci.qty END receiveqty,
       e.fullname receiver,cr.toacceptdate receivedate,
       csr.acceptanceqty completeqty,csr.completedate,e2.fullname completeemp,
       csd.checkemployeename,'正常批次' sourcetype,wfb.workflowname || ':' || wf.workflowrevision workflowinfo
FROM containershiprecord cr
LEFT JOIN containershiprecive csr ON csr.containershiprecordid = cr.containershiprecordid
LEFT JOIN containercurrentinfo cci ON cci.containerid = cr.containerid
LEFT JOIN containershiprecordstep csdd ON csdd.containershiprecordid = cr.containershiprecordid
LEFT JOIN Workflowstep ws ON ws.workflowstepid = csdd.workflowstepid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
LEFT JOIN containersubcontainer csc ON csc.containerid = cr.containerid AND csc.workflowstepid = csdd.workflowstepid --热表批次号
INNER JOIN containercurrentinfo subc ON subc.containerid = csc.subcontainerid
LEFT JOIN employee e ON e.employeeid = cr.ToAcceptor --热表接收人
LEFT JOIN employee e2 ON e2.employeeid = csr.employeeid --热表完成人
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN processdealrecord pdr ON pdr.parentid = cr.containershiprecordid AND pdr.processstatus = 0 AND (pdr.processtype = 1 OR pdr.processtype = 4)
LEFT JOIN employee e5 ON e5.employeeid = pdr.employeeid --拒收人
LEFT JOIN containersteprecord csd ON csd.containerid = cr.containerid AND csd.workflowstepid = csdd.workflowstepid
LEFT JOIN workflow wf ON wf.workflowid = NVL(subc.bsworkflowid,subc.workflowid)
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
WHERE cr.isuse = 0 ";

        //承制分厂
        if (jObject["tofactoryid"] != null && jObject["tofactoryid"].ToString() != "")
        {
            sql += string.Format(" AND cr.tofactoryid = '{0}'", jObject["tofactoryid"].ToString());
        }

        //发出分厂
        if (jObject["fromfactoryid"] != null && jObject["fromfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["fromfactoryid"].ToString());
        }

        //机型
        if (jObject["familylistnames"] != null && jObject["familylistnames"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames = '{0}'", jObject["familylistnames"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //主制分厂批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //承制单位批次号
        if (jObject["rbcontainername"] != null && jObject["rbcontainername"].ToString() != "")
        {
            sql += string.Format(" AND subc.containername = '{0}'", jObject["rbcontainername"].ToString());
        }

        //热表接收人
        if (jObject["receiver"] != null && jObject["receiver"].ToString() != "")
        {
            sql += string.Format(" AND cr.toacceptor = '{0}'", jObject["receiver"].ToString());
        }

        //热表接收日期
        if (jObject["recivedate"] != null && jObject["recivedate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["recivedate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(cr.toacceptdate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(cr.toacceptdate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //热表完成人
        if (jObject["completeemp"] != null && jObject["completeemp"].ToString() != "")
        {
            sql += string.Format(" AND csr.employeeid = '{0}'", jObject["completeemp"].ToString());
        }

        //热表完成日期
        if (jObject["completedate"] != null && jObject["completedate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["completedate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(csr.completedate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(csr.completedate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //工序号
        if (jObject["specno"] != null && jObject["specno"].ToString() != "")
        {
            sql += string.Format(" AND s.specno LIKE '%{0}%'", jObject["specno"].ToString());
        }

        //数据来源
        if (jObject["sourcetype"] != null && jObject["sourcetype"].ToString() == "无订单批次")
        {
            sql += " AND 1=0 ";
        }

        sql += @"
UNION ALL

SELECT cci.mfgordername,u1.attributevalue fromfactory,
       cci.productname,cci.productdescription,u.attributevalue containername,
       cci.containername rbcontainername,cci.familylistnames,ws.workflowstepname,s.specno,
       cci.qty receiveqty,
       e.fullname receiver,rb.receivedate,
       CASE WHEN rb.completedate IS NOT NULL THEN cci.qty ELSE NULL END completeqty,
       rb.completedate,e2.fullname completeemp,
       NULL checkemployeename,'无订单批次' sourcetype,
       wfb.workflowname || ':' || wf.workflowrevision workflowinfo 
FROM containercurrentinfo cci
INNER JOIN userattribute u ON u.parentid = cci.containerid AND u.userattributename = '委托批次'
INNER JOIN userattribute u1 ON u1.parentid = cci.containerid AND u1.userattributename = '委托单位'
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
LEFT JOIN workflowstep ws ON ws.workflowid = NVL(cci.bsworkflowid,cci.workflowid)
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
INNER JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN workflow wf ON wf.workflowid = NVL(cci.bsworkflowid,cci.workflowid)
LEFT JOIN workflowbase wfb ON wfb.workflowbaseid = wf.workflowbaseid
LEFT JOIN rbordercontainerreceive rb ON rb.containerid = cci.containerid
LEFT JOIN employee e ON e.employeeid = rb.receiveemployeeid
LEFT JOIN employee e2 ON e2.employeeid = rb.completeemployeeid
WHERE 1=1 ";
        //承制分厂
        if (jObject["tofactoryid"] != null && jObject["tofactoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["tofactoryid"].ToString());
        }

        //发出分厂
        if (jObject["fromfactoryid"] != null && jObject["fromfactoryid"].ToString() != "")
        {
            sql += string.Format(" AND cci.originalfactoryid = '{0}'", jObject["fromfactoryid"].ToString());
        }

        //机型
        if (jObject["familylistnames"] != null && jObject["familylistnames"].ToString() != "")
        {
            sql += string.Format(" AND cci.familylistnames = '{0}'", jObject["familylistnames"].ToString());
        }

        //零件图号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        //主制分厂批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        //承制单位批次号
        if (jObject["rbcontainername"] != null && jObject["rbcontainername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", jObject["rbcontainername"].ToString());
        }
        
        //工序号
        if (jObject["specno"] != null && jObject["specno"].ToString() != "")
        {
            sql += string.Format(" AND s.specno LIKE '%{0}%'", jObject["specno"].ToString());
        }

        //数据来源
        if (jObject["sourcetype"] != null && jObject["sourcetype"].ToString() == "正常批次")
        {
            sql += " AND 1=0 ";
        }

        //无订单批次委托单位
        if (jObject["wtdw"] != null && jObject["wtdw"].ToString() != "")
        {
            sql += string.Format(" AND u1.attributevalue LIKE '%{0}%'", jObject["wtdw"].ToString());
        }

        //无订单批次委托批次
        if (jObject["wtpc"] != null && jObject["wtpc"].ToString() != "")
        {
            sql += string.Format(" AND u.attributevalue LIKE '%{0}%'", jObject["wtpc"].ToString());
        }

        //热表接收人
        if (jObject["receiver"] != null && jObject["receiver"].ToString() != "")
        {
            sql += string.Format(" AND e.employeeid = '{0}'", jObject["receiver"].ToString());
        }

        //热表接收日期
        if (jObject["recivedate"] != null && jObject["recivedate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["recivedate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(rb.receivedate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(rb.receivedate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }

        //热表完成人
        if (jObject["completeemp"] != null && jObject["completeemp"].ToString() != "")
        {
            sql += string.Format(" AND e2.employeeid = '{0}'", jObject["completeemp"].ToString());
        }

        //热表完成日期
        if (jObject["completedate"] != null && jObject["completedate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["completedate"].ToString());
            if (arr.Count == 2)
            {
                sql += string.Format(" AND TRUNC(rb.completedate) >= TO_DATE('{0}','yyyy-mm-dd')", arr[0].ToString());
                sql += string.Format(" AND TRUNC(rb.completedate) <= TO_DATE('{0}','yyyy-mm-dd')", arr[1].ToString());
            }
        }
        
        return sql;
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = getSearchSqlString(jObject);
        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        if (jObject["tofactoryname"] != null && jObject["tofactoryname"].ToString() != "")
        {
            sql += string.Format(" AND f2.factoryname = '{0}'", jObject["tofactoryname"].ToString());
        }

        dtResult.Columns["sourcetype"].Caption = "数据来源";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["fromfactory"].Caption = "委托单位";
        dtResult.Columns["productname"].Caption = "零件号";
        dtResult.Columns["productdescription"].Caption = "名称";
        dtResult.Columns["containername"].Caption = "委托单位批次号";
        //dtResult.Columns["childcontainername"].Caption = "子序号";
        dtResult.Columns["rbcontainername"].Caption = "承制单位批次号";
        dtResult.Columns["familylistnames"].Caption = "型别";
        dtResult.Columns["workflowstepname"].Caption = "工序内容";
        dtResult.Columns["specno"].Caption = "工序号";
        dtResult.Columns["receiveqty"].Caption = "收入数量";
        dtResult.Columns["receiver"].Caption = "收入者";
        dtResult.Columns["receivedate"].Caption = "收入时间";
        dtResult.Columns["completeqty"].Caption = "完成数量";
        dtResult.Columns["completedate"].Caption = "完成时间";
        dtResult.Columns["completeemp"].Caption = "完成人";
        dtResult.Columns["checkemployeename"].Caption = "检验员";
        dtResult.Columns["workflowinfo"].Caption = "工艺信息";

        ExportHelper.ExportExcel(dtResult, jObject["tofactoryname"].ToString() + "零组件收发台账");
    }
}